<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="父级日志ID" prop="parentId">
              <el-input v-model="queryParams.parentId" placeholder="请输入父级日志ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单ID" prop="orderId">
              <el-input v-model="queryParams.orderId" placeholder="请输入订单ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="A端订单ID" prop="orderAid">
              <el-input v-model="queryParams.orderAid" placeholder="请输入A端订单ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="操作名称" prop="operate">
              <el-input v-model="queryParams.operate" placeholder="请输入操作名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="参数" prop="paramsLog">
              <el-input v-model="queryParams.paramsLog" placeholder="请输入参数" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="返回数据" prop="returnLog">
              <el-input v-model="queryParams.returnLog" placeholder="请输入返回数据" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="耗时" prop="time">
              <el-input v-model="queryParams.time" placeholder="请输入耗时" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['system:orderLog:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table ref="orderLogTableRef" v-loading="loading" :data="orderLogList">
        <el-table-column label="订单ID" align="center" prop="orderId" />
        <el-table-column label="A端订单ID" align="center" prop="orderAid" />
        <el-table-column label="操作名称" align="center" prop="operate" />
        <el-table-column label="参数" align="center" prop="paramsLog" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link :underline="false" @click="handlerViewCode(row.paramsLog)">{{ row.paramsLog }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="返回数据" align="center" prop="returnLog" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link :underline="false" @click="handlerViewCode(row.returnLog)">{{ row.returnLog }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="耗时" align="center" prop="time" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="getOrderChildLog(scope.row)" v-hasPermi="['system:orderLog:remove']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:orderLog:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[20, 50, 100, 300]"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <viewCode ref="viewCodeRef" />

    <!-- 添加或修改订单日志对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="orderLogFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级日志ID" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="orderLogOptions"
            :props="{ value: 'logId', label: 'operate', children: 'children' }"
            value-key="logId"
            placeholder="请选择父级日志ID"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="A端订单ID" prop="orderAid">
          <el-input v-model="form.orderAid" placeholder="请输入A端订单ID" />
        </el-form-item>
        <el-form-item label="操作名称" prop="operate">
          <el-input v-model="form.operate" placeholder="请输入操作名称" />
        </el-form-item>
        <el-form-item label="参数" prop="paramsLog">
          <el-input v-model="form.paramsLog" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="返回数据" prop="returnLog">
          <el-input v-model="form.returnLog" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="耗时" prop="time">
          <el-input v-model="form.time" placeholder="请输入耗时" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="sonDialog" title="日志详情" width="1200px">
      <el-timeline v-loading="childLoading" v-if="orderChildLogList.length || childLoading">
        <el-timeline-item v-for="(activity, index) in orderChildLogList" :key="index">
          <el-collapse v-model="activeNameChild" accordion>
            <el-collapse-item :title="activity.operate" :name="index">
              <template #title>
                {{ activity.operate }}
                <span class="text-[#666] ml-5">{{ activity.updateTime }}</span>
              </template>
              <div class="grid grid-cols-2 gap-3">
                <div>
                  <div>请求参数</div>
                  <JsonViewer :value="activity.paramsLog" :expand-depth="1" copyable sort theme="dark" />
                </div>
                <div>
                  <div>返回数据</div>
                  <JsonViewer :value="activity.returnLog" :expand-depth="1" copyable sort theme="dark" />
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
          <div class="flex items-center mt-4 gap-10 text-[#666] justify-end">
            <span>耗时：{{ activity.time }}ms</span>
          </div>
        </el-timeline-item>
      </el-timeline>
      <el-empty description="暂无日志详情" v-else> </el-empty>
    </el-dialog>
  </div>
</template>

<script setup name="OrderLog" lang="ts">
import { listOrderLog, getOrderLog, delOrderLog, addOrderLog, updateOrderLog } from '@/api/system/orderLog';
import { OrderLogVO, OrderLogQuery, OrderLogForm } from '@/api/system/orderLog/types';
import viewCode from './components/viewCode.vue';

type OrderLogOption = {
  logId: number;
  operate: string;
  children?: OrderLogOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const orderLogList = ref<OrderLogVO[]>([]);
const orderLogOptions = ref<OrderLogOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const orderLogFormRef = ref<ElFormInstance>();
const orderLogTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderLogForm = {
  logId: undefined,
  parentId: undefined,
  orderId: undefined,
  orderAid: undefined,
  operate: undefined,
  paramsLog: undefined,
  returnLog: undefined,
  time: undefined
};

const data = reactive<PageData<OrderLogForm, OrderLogQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    queryParent: true,
    orderId: undefined,
    orderAid: undefined,
    operate: undefined,
    paramsLog: undefined,
    returnLog: undefined,
    time: undefined,
    sortType: 2,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);
const total = ref(0);
/** 查询订单日志列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrderLog(queryParams.value);
  const data = proxy?.handleTree<OrderLogVO>(res.rows, 'logId', 'parentId');
  if (data) {
    orderLogList.value = data;
    total.value = res.total;
    loading.value = false;
  }
};

/** 查询订单日志下拉树结构 */
const getTreeselect = async () => {
  const res = await listOrderLog();
  orderLogOptions.value = [];
  const data: OrderLogOption = { logId: 0, operate: '顶级节点', children: [] };
  data.children = proxy?.handleTree<OrderLogOption>(res.data, 'logId', 'parentId');
  orderLogOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  orderLogFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: OrderLogVO) => {
  reset();
  getTreeselect();
  if (row != null && row.logId) {
    form.value.parentId = row.logId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加订单日志';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(orderLogList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: OrderLogVO[], status: boolean) => {
  data.forEach((item) => {
    orderLogTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: OrderLogVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getOrderLog(row.logId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改订单日志';
};

/** 提交按钮 */
const submitForm = () => {
  orderLogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.logId) {
        await updateOrderLog(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addOrderLog(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: OrderLogVO) => {
  await proxy?.$modal.confirm('是否确认删除订单日志编号为"' + row.logId + '"的数据项？');
  loading.value = true;
  await delOrderLog(row.logId).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const viewCodeRef = ref(null);
const handlerViewCode = (str) => {
  viewCodeRef.value.show = true;
  viewCodeRef.value.codeData = isJSON(str) ? JSON.parse(str) : str;
};
function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
}

const sonDialog = ref(false);
const childLoading = ref(false);
const orderChildLogList = ref([]);
const activeNameChild = ref('');
const ChildQueryParams = reactive({
  pageSize: 999,
  pageNum: 1,
  parentId: 0,
  sortType: 1
});
const getOrderChildLog = async (row: OrderLogVO) => {
  sonDialog.value = true;
  ChildQueryParams.parentId = row.logId;
  childLoading.value = true;
  let res = await listOrderLog(ChildQueryParams);
  if (res) {
    orderChildLogList.value = res.rows.map((item) => {
      if (isJSON(item.returnLog)) {
        item.returnLog = JSON.parse(item.returnLog);
      }
      if (isJSON(item.paramsLog)) {
        item.paramsLog = JSON.parse(item.paramsLog);
      }
      return item;
    });
    childLoading.value = false;
  }
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-link) {
  display: flex !important;
  justify-content: flex-end;
  gap: 6px;
  margin-bottom: 10px;
  width: fit-content;
}
.parent {
  transform: translateX(-100%);
  width: 100%;
  transition: 0.5s;
  &.show {
    transform: translateX(0);
    transition: 0.5s;
  }
}
:deep(.el-collapse-item__header) {
  border-bottom: none;
  border-top: none;
}
:deep(.el-collapse) {
  border-bottom: none;
  border-top: none;
}
:deep(.el-collapse-item) {
  box-shadow: 0px 0px 10px 0px rgb(0 0 0 / 6%);
  border-radius: 10px;
  padding-inline: 10px;
  background-color: #fff;
  &.is-active {
    padding-bottom: 20px;
  }
}
:deep(.el-collapse-item__wrap) {
  border-bottom: none;
}
:deep(.el-timeline) {
  padding-left: 0;
}
</style>
